//
//  classifyDetailsViewController.m
//  livingDesign
//
//  Created by dlios on 15-1-28.
//  Copyright (c) 2015年 怡居. All rights reserved.
//





#import "ClassifyDetailsViewController.h"
#import "ASIHTTPRequest.h"
#import "Classify.h"
#import "myDetailsCell.h"
#import "MJRefresh.h"
#import "NewestDetailViewController.h"
#import "SouSuoViewController.h"


@interface ClassifyDetailsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, retain)NSMutableArray *classifyArr;//用来装数据的数组
@property (nonatomic, retain)Classify *classify;
@property (nonatomic, retain)UICollectionView *collectionView;//界面视图
@property (nonatomic, assign)NSInteger Z;


@end

@implementation ClassifyDetailsViewController
//数据的懒加载
- (NSMutableArray *)classifyArr
{
    if (!_classifyArr) {
        self.classifyArr = [NSMutableArray array];
        
        for (int i = 0; i<10; i++) {
           
         
        }
    }
    return _classifyArr;
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.classifyArr = [NSMutableArray array];
        
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.Z = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo.png"] style:UIBarButtonItemStyleDone target:self action:@selector(sousuoAction:)];
    

    
    //铺设界面
    
    UICollectionViewFlowLayout *detailsVFL = [[UICollectionViewFlowLayout alloc] init];
    detailsVFL.itemSize = CGSizeMake(self.view.bounds.size.width / 2 - 1, 200);
    detailsVFL.minimumInteritemSpacing = 0.5;
    detailsVFL.minimumLineSpacing = 1;
    
    
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:detailsVFL];
    self.collectionView.backgroundColor = [UIColor colorWithRed:102 green:102 blue:102 alpha:0.8];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:_collectionView];
    [_collectionView release];
    [detailsVFL release];
    //重用池
    [self.collectionView registerClass:[myDetailsCell class] forCellWithReuseIdentifier:@"suibian"];
    

    
       // 2.集成刷新控件
    [self addHeader];
    [self addFooter];
    
   
    
    //初始化数组
//    self.classifyArr = [NSMutableArray array];
    
    

    //使用ASI网络请求
    NSString *name =self.stu1;
    //拼接字符串,前11为一种接法,第11个为单独的(原因:名字编译后的网址与原网址不符),其他的又是一种接法
    
    if (name != nil) {
        //设置标题
        self.title = self.stu1;
        NSString *strD =@"http://rm.app.diaoyuweng.com/json_rm.php?action=list&ver=4&page=0&category=jiaju&category2=&pageSize=10&appCookie=channel_AppStore%20version_4.1.2%20oid_0f607264fc6318a92b9e13c65db7cd3c%20package_com.aslibra.rm.jiaju%20platform_iphone%20ver_8.1.2%20jb_0&keyword=%E8%A3%85%E4%BF%AE%E6%94%BB%E7%95%A5";
        NSString *newStr1 = [strD stringByReplacingOccurrencesOfString:@"%E8%A3%85%E4%BF%AE%E6%94%BB%E7%95%A5" withString:name];
        newStr1 = [newStr1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:newStr1];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        request.delegate = self;
        [request startAsynchronous];
        
        
    }else if (self.stu3 != nil){
        self.title = self.stu3;
        NSString *strD = @"http://rm.app.diaoyuweng.com/json_rm.php?action=list&ver=4&page=0&category=jiaju&category2=E&pageSize=10&appCookie=channel_AppStore%20version_4.1.2%20oid_0f607264fc6318a92b9e13c65db7cd3c%20package_com.aslibra.rm.jiaju%20platform_iphone%20ver_8.1.2%20jb_0";
        NSURL *url = [NSURL URLWithString:strD];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        request.delegate = self;
        [request startAsynchronous];
    }else{
        //设置标题
        self.title = self.stu2;
        
   NSString *strD = @"http://rm.app.diaoyuweng.com/json_rm.php?action=list&ver=4&page=0&category=jiaju&category2=%E5%85%B6%E4%BB%96&pageSize=10&appCookie=channel_AppStore%20version_4.1.2%20oid_0f607264fc6318a92b9e13c65db7cd3c%20package_com.aslibra.rm.jiaju%20platform_iphone%20ver_8.1.2%20jb_0";
        
    NSString *newStr2 = [strD stringByReplacingOccurrencesOfString:@"%E5%85%B6%E4%BB%96" withString:self.stu2];
    newStr2 = [newStr2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
    NSURL *url = [NSURL URLWithString:newStr2];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
        
  }
    
    
    

    
    
    //提前注册
    [self.collectionView registerClass:[myDetailsCell class] forCellWithReuseIdentifier:@"livingDesign1"];
    
   }


//将数据添加到大数组内
- (void)requestFinished:(ASIHTTPRequest *)request
{
    //解析数据
    NSData *data = [request responseData];
    NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
   
    NSArray *tempArr = [tempDic objectForKey:@"data"];
    for (NSDictionary *dataDic in tempArr) {
        self.classify = [[Classify alloc] init];
        [self.classify setValuesForKeysWithDictionary:dataDic];
        [self.classifyArr addObject:self.classify];
        [_classify release];
 }
  
    NSLog(@"---------====== %@",self.classifyArr);
    [self.collectionView reloadData];
  
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"请求失败");
}


//集成刷新空间方法

- (void)addHeader
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加下拉刷新头部控件
    [self.collectionView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        // 增加5条假数据
        for (int i = 0; i<10; i++) {
     
        }
        
        // 模拟延迟加载数据，因此2秒后才调用）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.collectionView reloadData];
            // 结束刷新
            [vc.collectionView headerEndRefreshing];
        });
    }];
    

}

- (void)addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    [self.collectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        //******** 数据添加*******//
         NSString *name =self.stu1;
        // 增加数据
//        for (int Z = 1; Z < 3; Z++) {
        
            if (name != nil) {
           
      
            NSString *strD =@"http://rm.app.diaoyuweng.com/json_rm.php?action=list&ver=4&page=Z&category=jiaju&category2=&pageSize=10&appCookie=channel_AppStore%20version_4.1.2%20oid_0f607264fc6318a92b9e13c65db7cd3c%20package_com.aslibra.rm.jiaju%20platform_iphone%20ver_8.1.2%20jb_0&keyword=%E8%A3%85%E4%BF%AE%E6%94%BB%E7%95%A5";
            NSString *newStr1 = [strD stringByReplacingOccurrencesOfString:@"%E8%A3%85%E4%BF%AE%E6%94%BB%E7%95%A5" withString:name];
            newStr1 = [newStr1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:newStr1];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
            request.delegate = self;
            [request startAsynchronous];
                self.Z++;
            
           
                
            
        }else if (self.stu3 != nil){
            self.title = self.stu3;
            NSString *strD = @"http://rm.app.diaoyuweng.com/json_rm.php?action=list&ver=4&page=Z&category=jiaju&category2=E&pageSize=10&appCookie=channel_AppStore%20version_4.1.2%20oid_0f607264fc6318a92b9e13c65db7cd3c%20package_com.aslibra.rm.jiaju%20platform_iphone%20ver_8.1.2%20jb_0";
            NSURL *url = [NSURL URLWithString:strD];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
            request.delegate = self;
            [request startAsynchronous];
            self.Z++;
            
        }else{
            //设置标题
            self.title = self.stu2;
            NSString *strD = @"http://rm.app.diaoyuweng.com/json_rm.php?action=list&ver=4&page=Z&category=jiaju&category2=%E5%85%B6%E4%BB%96&pageSize=10&appCookie=channel_AppStore%20version_4.1.2%20oid_0f607264fc6318a92b9e13c65db7cd3c%20package_com.aslibra.rm.jiaju%20platform_iphone%20ver_8.1.2%20jb_0";
            NSString *newStr2 = [strD stringByReplacingOccurrencesOfString:@"%E5%85%B6%E4%BB%96" withString:self.stu2];
            newStr2 = [newStr2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSURL *url = [NSURL URLWithString:newStr2];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
            request.delegate = self;
            [request startAsynchronous];
            self.Z++;
        }
        
        
//        }
        
        // 模拟延迟加载数据，因此2秒后才调用）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.collectionView reloadData];
            // 结束刷新
            [vc.collectionView footerEndRefreshing];
        });
    }];
}






//界面的两个方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.classifyArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    myDetailsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"livingDesign1" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    Classify  *classify = [self.classifyArr objectAtIndex:indexPath.row];
   
     //得到是图片网址,对其进行处理
    NSString *str2 = classify.img;
   
    //异步请求
    
    str2 = [str2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str2];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"GET";
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //3.对数据进行处理
        UIImage *image = [UIImage imageWithData:data];
        cell.imageView.image = image;
        cell.myLabel.text = classify.title;
        
  
        
    }];
    return cell;
}





//重写set方法
- (void)setIsAccessibilityElement:(BOOL)isAccessibilityElement
{
    self.stu1 = self.stu1;
    self.stu2 = self.stu2;
    self.stu3 = self.stu3;
}

//点击跳转页面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewestDetailViewController *newestDVC = [[NewestDetailViewController alloc] init];
    newestDVC.newestD= [self.classifyArr objectAtIndex:indexPath.item];
    
    [self.navigationController pushViewController:newestDVC animated:YES];
    [newestDVC release];
}

//点击搜索页面,跳转搜索页面
- (void)sousuoAction:(UIBarButtonItem *)barButton
{
    SouSuoViewController *sousuo = [[SouSuoViewController alloc] init];
    [self.navigationController pushViewController:sousuo animated:YES];
    [sousuo release];
}


- (void)dealloc
{
    [_classifyArr release];
    [_collectionView release];
    [_stu1 release];
    [_stu2 release];
    [_stu3 release];
    [_classify release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
